<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="name">
        <el-input v-model.trim="form.name" placeholder="请输入名称"></el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model.trim="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>

      <el-form-item prop="repassword">
        <el-input v-model.trim="form.repassword" placeholder="请再次确认密码"></el-input>
      </el-form-item>

      <el-form-item prop="mobile">
        <el-input v-model.trim="form.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (value === "") {
        callback(new Error("请再次输入手机号"));
      } else if (!reg.test(value)) {
        callback(new Error("手机输入格式不正确!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        name: "",
        password: "",
        repassword: "",
        mobile: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入活动名称", trigger: "change" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" },
        ],
        repassword: [{ validator: validatePass2, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },
    };
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate((valid) => {
        console.log(valid, 123);
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          alert("您输入不正确!");
          this.$refs.form.resetFields();
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
};
</script>
<style lang="less" scoped>
// .el-form {
//   width: 400px;
//   height: 350px;
//   margin: 200px auto;
// }
</style>
